import axios, { type AxiosResponse } from "axios";
import MessageBox from "@/utils/MessageBox.js"
import url from "@/utils/url.js";
import utils from "@/utils/utils.js";


const request = {
  app: null,
  secretKey: "", //二次加密密钥
  timeOut: 60000,
  useEncryption: url.useEncryption ? url.useEncryption : false, //发送请求方式 true: 加密  false: 不加密
  /**
   * post请求
   * @param data
   * @returns
   */
  rpc(data: {
    url?: string;
    name?: string;
    action?: any;
    failType?: string;
    customErrFlag?: boolean;
    sharding?: string;
  }) {
    const dataUrl = data.url || url.requestUrl;
    const name = data.name || '';
    const action = data.action || {};
    const sharding = data.sharding || '';
    const requestUrl = dataUrl + name;
    const failType = data.failType || 'danger';//错误弹窗类型
    const customErrFlag = data.customErrFlag || false;//是否自定义错误返回（在请求中错误不出提示框）
    const requestParam = {
      failType,
      customErrFlag
    }
    const json = JSON.stringify(action, (key, value) => {
      if (key.startsWith("$")) {
        return undefined;
      } else {
        return value;
      }
    });
    const requestBody = {
      content: json,
      service: name,
      sharding: sharding || '',
    }
    utils.consoleLog({
      title: '发送请求报文',
      url: requestUrl,
      color: '#ba904f',
      res: requestBody,
    })
    return new Promise((resove, reject) => {
      this.normallRequest(requestUrl, requestBody, requestParam)
        .then((res) => {
          resove(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  /**
   * 发送POST请求-正常发送
   * @param {String} requestUrl  接口名
   * @param {Object} requestBody  接口参数
   * @param {Boolean} requestParam   错误提示类型，是否为自定义错误提示展示，customErrFlag为true则这里不提示
   */
  normallRequest(requestUrl: any, requestBody: any, requestParam: any) {
    return new Promise((resolve, reject) => {
      axios({
        method: "POST",
        url: requestUrl,
        data: requestBody,
        xsrfCookieName: "JSESSIONID",
        xsrfHeaderName: "X-XSRF-TOKEN",
        headers: {
          "Content-Type": "application/json",
          uid: '-1',
          "User-Id": "",
          "Dept-code": "",
          scap_platform: "pc",
          scap_token: window.localStorage.getItem("scap_token") ? window.localStorage.getItem("scap_token") : "",
          user_agent: requestUrl == "pub.employee.SilenceLogin" ? "ygzx" : ""

        },
        timeout: request.timeOut,
        // responseType: 'arraybuffer'
      }).then((resp) => {
        this.disposeRpcResult(resp, requestParam, requestUrl).then(data => {
          // 处理 交互 成功的结果
          resolve(data);
        }).catch(error => {
          // 处理 交互 失败的结果
          reject(error);
        });
      }).catch(async (error) => {
        MessageBox.alert({ txt: '网络请求错误(' + error + ')', type: requestParam.failType }).then((res: any) => { }).catch(() => { })
        reject(error);
      });
    }).catch((error) => {
      const retMsg = error.retMsg || error;//错误展示信息
      let goLoginFlag = false;//是否返回登录页面
      if (String(retMsg).indexOf("code 500") != -1 || String(retMsg).indexOf("code 404") != -1) {
        // 接口连接出错通用提示
        if (!requestParam.customErrFlag) {
          MessageBox.alert({ txt: retMsg, type: requestParam.failType }).then(() => { }).catch(() => { })
        }
      } else {
        // 接口返回错误进行通用提示
        if (retMsg.indexOf("登录已过期") > -1 || retMsg.indexOf("请重新登录") > -1) {
          goLoginFlag = true;
        }
        if (retMsg.indexOf("审批") > -1 && retMsg.indexOf("请等待") > -1) {
          goLoginFlag = true;
        }
        // 是否自定义在catch中处理错误信息
        if (!requestParam.customErrFlag) {
          MessageBox.alert({ txt: retMsg, type: requestParam.failType }).then((res: any) => {
            // 是否登出
            if (goLoginFlag) {
              utils.closeDialogGoToLogin();//登出到登录页
            }
          }).catch(() => { })
        }
      }
      throw error;
    });
  },
  /**
  * 处理返回的数据（统一处理）
  */
  disposeRpcResult(result: AxiosResponse<any, any>, requestParam: any, requestUrl: string) {
    const data = Object.assign({}, result.data);
    const retCode = data.retCode;
    const retMsg = data.retMsg;
    // console.log('返回统一处理', {requestParam, result, data, retCode, retMsg})
    return new Promise((resolve, reject) => {
      // 系统异常抛出
      if (retCode == '9999' || retCode == '8999' || retCode == '2000' || retCode == '9800' || retCode == '4023') {
        utils.consoleLog({
          title: '请求响应异常信息',
          url: requestUrl,
          color: '#e0463c',
          res: data,
        })
        reject(data);
      } else {
        utils.consoleLog({
          title: '请求响应信息',
          url: requestUrl,
          color: '#56a032',
          res: data,
        })
        // 接口返回无异常
        resolve(data.action);
      }
    })
  },
}

export default request;